import nodemailer from 'nodemailer';

// 存储验证码的Map，格式：{ email: { code: string, expires: number } }
const verificationCodes = new Map<string, { code: string; expires: number }>();

// 邮件配置
const emailConfig = {
  development: {
    host: 'smtp.qq.com',
    port: 587,
    secure: false, // true for 465, false for other ports
    auth: {
      user: process.env.QQ_EMAIL_USER || 'your-qq-email@qq.com',
      pass: process.env.QQ_EMAIL_PASS || 'your-qq-authorization-code'
    }
  },
  production: {
    host: 'smtp.qq.com',
    port: 587,
    secure: false,
    auth: {
      user: process.env.QQ_EMAIL_USER || 'your-qq-email@qq.com',
      pass: process.env.QQ_EMAIL_PASS || 'your-qq-authorization-code'
    }
  }
};

// 创建邮件传输器
const createTransporter = () => {
  const config = process.env.NODE_ENV === 'production' 
    ? emailConfig.production 
    : emailConfig.development;
  
  return nodemailer.createTransport(config);
};

// 生成6位数字验证码
const generateVerificationCode = (): string => {
  return Math.floor(100000 + Math.random() * 900000).toString();
};

// 发送验证码邮件
export const sendVerificationCode = async (email: string): Promise<{ success: boolean; message: string; code?: string }> => {
  try {
    const code = generateVerificationCode();
    const expires = Date.now() + 10 * 60 * 1000; // 10分钟过期
    
    // 存储验证码
    verificationCodes.set(email, { code, expires });
    
    const transporter = createTransporter();
    
    // 邮件内容
    const mailOptions = {
      from: `"医疗系统" <${process.env.QQ_EMAIL_USER || 'your-qq-email@qq.com'}>`,
      to: email,
      subject: '医疗系统 - 密码重置验证码',
      html: `
        <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; background-color: #f8f9fa;">
          <div style="background-color: #ffffff; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
            <div style="text-align: center; margin-bottom: 30px;">
              <h1 style="color: #2c3e50; margin: 0; font-size: 24px;">🏥 医疗系统</h1>
              <p style="color: #7f8c8d; margin: 10px 0 0 0;">密码重置验证码</p>
            </div>
            
            <div style="background-color: #ecf0f1; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
              <p style="margin: 0 0 15px 0; color: #2c3e50; font-size: 16px;">
                您好！您正在重置医疗系统的登录密码。
              </p>
              <p style="margin: 0 0 15px 0; color: #2c3e50; font-size: 16px;">
                您的验证码是：
              </p>
              <div style="background-color: #3498db; color: white; padding: 15px; border-radius: 5px; text-align: center; font-size: 24px; font-weight: bold; letter-spacing: 3px;">
                ${code}
              </div>
            </div>
            
            <div style="background-color: #fff3cd; border: 1px solid #ffeaa7; padding: 15px; border-radius: 5px; margin-bottom: 20px;">
              <p style="margin: 0; color: #856404; font-size: 14px;">
                ⏰ <strong>验证码有效期：</strong>10分钟<br>
                🔒 <strong>安全提醒：</strong>请勿将验证码告诉他人
              </p>
            </div>
            
            <div style="text-align: center; color: #7f8c8d; font-size: 12px;">
              <p style="margin: 0;">
                此邮件由医疗系统自动发送，请勿回复。<br>
                如果您没有请求重置密码，请忽略此邮件。
              </p>
            </div>
          </div>
        </div>
      `
    };
    
    // 发送邮件
    const info = await transporter.sendMail(mailOptions);
    
    if (process.env.NODE_ENV === 'development') {
      console.log('📧 开发模式 - 邮件发送成功');
      console.log('📧 验证码:', code);
      console.log('📧 预览URL:', nodemailer.getTestMessageUrl(info));
    }
    
    return { 
      success: true, 
      message: '验证码发送成功',
      code: process.env.NODE_ENV === 'development' ? code : undefined
    };
    
  } catch (error) {
    console.error('❌ 发送邮件失败:', error);
    return { 
      success: false, 
      message: '发送邮件失败，请检查邮箱配置' 
    };
  }
};

// 验证验证码
export const verifyCode = (email: string, code: string): { success: boolean; message: string } => {
  const stored = verificationCodes.get(email);
  
  if (!stored) {
    return { success: false, message: '验证码不存在或已过期' };
  }
  
  if (Date.now() > stored.expires) {
    verificationCodes.delete(email);
    return { success: false, message: '验证码已过期' };
  }
  
  if (stored.code !== code) {
    return { success: false, message: '验证码错误' };
  }
  
  // 验证成功后删除验证码
  verificationCodes.delete(email);
  return { success: true, message: '验证成功' };
};

// 清理过期的验证码
const cleanupExpiredCodes = () => {
  const now = Date.now();
  for (const [email, data] of verificationCodes.entries()) {
    if (now > data.expires) {
      verificationCodes.delete(email);
    }
  }
};

// 每5分钟清理一次过期验证码
setInterval(cleanupExpiredCodes, 5 * 60 * 1000);
